package com.pig4cloud.common.seate.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
import com.pig4cloud.common.seate.init.SeateRunner;
import com.typesafe.config.ConfigFactory;
import io.seata.config.AbstractConfiguration;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;

/**
 * 获取文件配置
 *
 * @author lw
 */
@Slf4j
@NoArgsConstructor
public abstract class BaseSeataConfig extends AbstractConfiguration {

    protected static final Dict DATA = Dict.create();

    /**
     * 获取文件配置
     */
    static {
        DATA.set("seateFileProperties", SeateRunner.dict.getBean("seateFileProperties"))
                .set("seateRegisterProperties", SeateRunner.dict.getBean("seateRegisterProperties"))
                .set("seateRegisterConfigProperties", SeateRunner.dict.getBean("seateRegisterConfigProperties"));
    }


    public BaseSeataConfig(String name) {
        URL resource = this.getClass().getClassLoader().getResource(name);
        if (null != resource) {
            Dict json = name.equalsIgnoreCase("file.conf") ? BeanUtil.mapToBean(BeanUtil.beanToMap(DATA.getBean("seateFileProperties")), Dict.class, false)
                    : BeanUtil.mapToBean(BeanUtil.beanToMap(DATA.getBean("seateRegisterProperties")), Dict.class, false);
            Dict dict = Dict.create();
            json = name.equalsIgnoreCase("file.conf") ? dict.set("store", JSONUtil.toBean(JSONUtil.toJsonStr(json), Dict.class)) :
                    dict.set("registry", JSONUtil.toBean(JSONUtil.toJsonStr(json), Dict.class)).set("config", JSONUtil.toBean(JSONUtil.toJsonStr(BeanUtil.beanToMap(DATA.getBean("seateRegisterConfigProperties"))), Dict.class));
            DATA.set("targetFilePath", resource.getPath()).set("fileConfig", ConfigFactory.parseMap(json));
            if (log.isInfoEnabled()) {
                log.info("The configuration file used is {}", name);
            }
        }

    }


}
